﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ServiceManager.Utils;
using ServiceStack.Redis;

namespace QuotationService.RealtimeQuotation
{
    /// <summary>
    /// 格式化方法
    /// </summary>
    static partial class Format
    {
        /// <summary>
        /// QuotationDataType的格式化方法
        /// </summary>
        /// <param name="qdt"></param>
        /// <returns></returns>
        public static string ToFormatString(this QuotationDataType qdt)
        {
            return ((int)qdt).ToString("00");
        }

        /// <summary>
        /// QuotationSource的格式化方法
        /// </summary>
        /// <param name="qs"></param>
        /// <returns></returns>
        public static string ToFormatString(this QuotationSource qs)
        {
            return qs.ToString().PadLeft(3, '0');
        }
    }

    /// <summary>
    /// 行情频道基类
    /// 用于控制行情发布订阅的频道格式
    /// </summary>
    [DebuggerNonUserCode]
    public class QuotationChannel
    {
        /// <summary>
        /// 行情数据源
        /// </summary>
        public QuotationSource Source { get; protected set; }

        /// <summary>
        /// 行情数据类型
        /// </summary>
        public QuotationDataType DataType { get; protected set; }

        /// <summary>
        /// 商品代码
        /// </summary>
        public string Code { get; protected set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dataType"></param>
        /// <param name="code"></param>
        public QuotationChannel(QuotationSource source, QuotationDataType dataType = QuotationDataType.All, string code = "")
        {
            if (source == null)
                throw new ArgumentNullException("source");

            this.Source = source;
            this.DataType = dataType;
            this.Code = code;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="channel"></param>
        public QuotationChannel(string channel)
        {
            this.Source = channel.Substring(0, 3);
            this.DataType = (QuotationDataType)Int32.Parse(channel.Substring(4, 2));

            if (channel.Length >= 17)
                this.Code = channel.Substring(7, 10).TrimStart(new char[] { '#' });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        internal virtual string ToSubscribeChannel()
        {
            string dataType = this.DataType.ToFormatString();
            if (this.DataType == QuotationDataType.All)
                dataType = "??";

            string code = this.Code;
            if (string.IsNullOrEmpty(code))
                code = "??????????";

            return this.Source.ToFormatString() + ":" + dataType + ":" + code.PadLeft(10, '#');
        }
    }

}
